#include "file_service.h"

// 获取指定目录下所有mp4文件信息存入顺序表
int get_video_path(arr_list *list, char *dirpath) {
    DIR *dirp = NULL;
    video *new = NULL;
    dirp = opendir(dirpath);  // 打开目录
    if (NULL == dirp) {
        perror("opendir");
        return -1;
    }

    struct dirent *dir_file = NULL;
    char *pFile = NULL; // 用于保存后缀

    // 遍历目录内容
    while ((dir_file = readdir(dirp)) != NULL) {
        if (dir_file->d_type == DT_REG ) { // 判断普通文件
            printf("d_name = %s\n", dir_file->d_name);
            pFile = NULL;
            pFile = strrchr(dir_file->d_name, '.'); // 判断输入的文件名最后输出.的位置
            if (pFile != NULL && strncmp(pFile, ".mp4", 4) == 0) { // 后缀为.mp4的文件
                new = (video *)malloc(sizeof(video));
                // 存文件绝对路径
                strcat(new->absolute_path, dirpath);
                strcat(new->absolute_path, dir_file->d_name);
                // 存文件名
                strcpy(new->name, dir_file->d_name);
                // 存入顺序表
                sequence_insert(list, new);
            }
        }
    }
    // 关闭目录
    int ret = closedir(dirp);
    if (-1 == ret) {
        perror("closedir");
        return -1;
    }
    // // 输出存入的绝对路径
    // sequence_print_video(list);
    return 0;
}

// 获取指定目录下所有bmp预览图文件信息存入顺序表
int get_video_preview(arr_list *list, char *dirpath) {
    DIR *dirp = NULL;
    video *new = NULL;
    dirp = opendir(dirpath);  // 打开目录
    if (NULL == dirp) {
        perror("opendir");
        return -1;
    }

    struct dirent *dir_file = NULL;
    char *pFile = NULL; // 用于保存后缀
    char video_name[32];  // 保存视频名称
    // 遍历目录内容
    while ((dir_file = readdir(dirp)) != NULL) {
        if (dir_file->d_type == DT_REG ) { // 判断普通文件
            pFile = NULL;
            pFile = strrchr(dir_file->d_name, '.'); // 判断输入的文件名最后输出.的位置
            if (pFile != NULL && strncmp(pFile, ".bmp", 4) == 0) { // 后缀为.nmp的文件
                // 现在是要将预览图路径放到对应的视频节点(联系是视频名与预览图名相同)
                for (int i = 0; i < list->size; i++) {
                    memset(video_name, 0, sizeof(video_name));
                    strcpy(video_name, ((video *)(list->data[i]))->name);  // 赋值
                    if (strstr(dir_file->d_name, strtok(video_name, "."))) { // 将截取后缀的视频名与找到的文件名比较，是否是子串
                        printf("d_name = %s\n", dir_file->d_name);
                        strcat(((video *)(list->data[i]))->preview_path, dirpath);
                        strcat(((video *)(list->data[i]))->preview_path, dir_file->d_name);
                    }
                }
            }
        }
    }
    // 关闭目录
    int ret = closedir(dirp);
    if (-1 == ret) {
        perror("closedir");
        return -1;
    }
    return 0;
}